<?php
namespace Hawk\Controller;
use \Hawk\Controller\IndexController;
class AdminController extends IndexController 
{
    /**
     * 管理员添加
     * @author hawk <2271030162@qq.com>
     * @return mix
     */
    public function add()
    {
    	if(IS_POST)
    	{
    		$model = D('Hawk/Admin');
    		if($model->create(I('post.'), 1))
    		{
    			if($id = $model->add())
    			{    
                    //写入操作日志
                    $content = "成功添加用户".$_POST['username'];
                    hawk_operation_log(session('id'),hawk_get_ip(),$content);
    				$this->success('添加成功！', U('lst?p='.I('get.p')));
    				exit;
    			}else{
                    //写入操作日志
                    $content = "添加用户".$_POST['username']."失败";
                    hawk_operation_log(session('id'),hawk_get_ip(),$content);
                }
    		}
    		$this->error($model->getError());
    	}
        //查询角色
        $armodel = M('AdminRole');
        $role_id =$armodel->where('admin_id='.$_SESSION['staff_info']['id'])->select();
        if($role_id[0]['admin_id']==1){
            $pmodel = M('role');
            $parr = $pmodel->select();
            $this->assign('parr',$parr);
            //查询部门
            $pamodel = M('Part');
            $part = $pamodel->select();
        }else{
            $armodel = M('AdminRole');
            $role_id = $armodel->where('admin_id='.$_SESSION['staff_info']['id'])->select();
            $pmodel = M('role');
            if(is_array($role_id)){
                for ($i=0; $i <count($role_id) ; $i++) { 
                    $parr[$i] = $pmodel->find($role_id[$i]['role_id']);
                    $parr[$i]['child'] = $pmodel->where('pid='.$role_id[$i]['role_id'])->select();
                }  
            }
            $this->assign('parr',$parr[0]['child']);
            //查询部门
            $model = D('Hawk/Admin');
            $where['pid']=$_SESSION['staff_info']['part_id'];
            $pamodel = M('Part');
            $past_self = $pamodel->find($_SESSION['staff_info']['part_id']);
            $part = $pamodel->where($where)->select();
            array_unshift($part,$past_self);
        }
        $this->assign('part',$part); 
		$this->setPageBtn('添加管理员', '管理员列表', U('lst?p='.I('get.p')));
		$this->display();
    }
    /**
     * 管理员修改
     * @author hawk <2271030162@qq.com>
     * @return mix
     */
    public function edit()
    {
    	$id = I('get.id');
    	if(IS_POST)
    	{
    		$model = D('Hawk/Admin');
    		if($model->create(I('post.'), 2))
    		{
                // hecho($_POST);die;
                $user = $model->find($id);
    			if($model->save() !== FALSE)
    			{
                    //写入操作日志
                    $content = "成功修改用户".$user['username'];
                    hawk_operation_log(session('id'),hawk_get_ip(),$content);
    				$this->success('修改成功！', U('lst', array('p' => I('get.p', 1))));
    				exit;
    			}else{
                    //写入操作日志
                    $content = "修改用户".$user['username']."失败";
                    hawk_operation_log(session('id'),hawk_get_ip(),$content);
                }
    		}
    		$this->error($model->getError());
    	}
    	$model = M('Admin');
    	$data = $model->find($id);
    	$this->assign('data', $data);
        //查询角色
        $armodel = M('AdminRole');
        $role_id =$armodel->where('admin_id='.$_SESSION['staff_info']['id'])->select();
        if($role_id[0]['admin_id']==1 || session('id')==1){
            //查询角色
            $pmodel = M('role');
            $parr = $pmodel->select();
            $this->assign('parr',$parr);
            //查询部门
            $pamodel = M('Part');
            $part = $pamodel->select();           
        }else{
            $armodel = M('AdminRole');
            $role_id = $armodel->where('admin_id='.$_SESSION['staff_info']['id'])->select();
            $pmodel = M('role');
            if(is_array($role_id)){
                for ($i=0; $i <count($role_id) ; $i++) { 
                    $parr[$i] = $pmodel->find($role_id[$i]['role_id']);
                    $parr[$i]['child'] = $pmodel->where('pid='.$role_id[$i]['role_id'])->select();
                    $role_self = $pmodel->find($role_id[$i]['role_id']);
                    array_unshift($parr[$i]['child'],$role_self);
                }  
            }
            $this->assign('parr',$parr[0]['child']);
            //查询部门
            $model = D('Hawk/Admin');
            $where['pid']=$_SESSION['staff_info']['part_id'];
            $pamodel = M('Part');
            $past_self = $pamodel->find($_SESSION['staff_info']['part_id']);
            $part = $pamodel->where($where)->select();
            array_unshift($part,$past_self);
        }
        //查询管理员拥有的角色
        $armodel = M('AdminRole');
        $ardata = $armodel->where('admin_id='.$id)->select();
        //重组一维数组
        $role = array();
        //print_r($ardata);die;
        foreach ($ardata as $key => $value) {
            $role[]=$value['role_id'];
        }
        $this->assign('role',$role);
        $this->assign('part',$part);
		$this->setPageBtn('修改管理员', '管理员列表', U('lst?p='.I('get.p')));
		$this->display();
    }
    /**
     * 管理员禁用
     * @author hawk <2271030162@qq.com>
     * @return mix
     */
    public function recycle()
    {
        if (!empty($_POST['id']) && $_POST['id']!=1) {
            $model = M('Admin');
            if($_POST['is_use']==1){

                $keyword = '禁用';

                $data['is_use']=0;  
            }else{

                $keyword = '恢复';

                $data['is_use']=1;
            } 
               
            $re = $model->where('id='.$_POST['id'])->data($data)->save();

            $user = $model->find($id);

            if($re!==false){
                //写入操作日志
                $content = "成功".$keyword."用户".$user['username'];

                hawk_operation_log(session('id'),hawk_get_ip(),$content);

                echo json_encode(array('code'=>1,'msg'=>'设置成功！'));exit;
            }else{
                //写入操作日志
                $content = $keyword."用户".$user['username']."失败";

                hawk_operation_log(session('id'),hawk_get_ip(),$content);

                echo json_encode(array('code'=>0,'msg'=>'设置失败！'));exit;
            }
        }else{
            echo json_encode(array('code'=>0,'msg'=>'无此权限'));exit;
        }
    }
    /**
     * 管理员删除
     * @author hawk <2271030162@qq.com>
     * @return mix
     */
    public function delete()
    {
    	$model = D('Hawk/Admin');

        $user = $model->find($id);

    	if($model->delete(I('get.id', 0)) !== FALSE)
    	{
            //写入操作日志
            $content = "成功删除用户".$user['username'];

            hawk_operation_log(session('id'),hawk_get_ip(),$content);

    		$this->success('删除成功！', U('lst', array('p' => I('get.p', 1))));
    		exit;
    	}
    	else 
    	{
            //写入操作日志
            $content = "删除用户".$user['username']."失败";

            hawk_operation_log(session('id'),hawk_get_ip(),$content);
            
    		$this->error($model->getError());
    	}
    }
    /**
     * 管理员列表
     * @author hawk <2271030162@qq.com>
     * @return mix
     */
    public function lst()
    {
        if(IS_POST){
            if(!empty($_POST['username'])){
                $search['username']=$_POST['username'];
            }
            if(!empty($_POST['nickname'])){
                $search['nickname']=$_POST['nickname'];
            }
            if(!empty($_POST['part_id'])){
                $search['part_id']=$_POST['part_id'];
            }
        }
        if(!empty($search)){
            $where=$search;
        }else{
            $where=array();
        }      
        $model=M('');
    	$amodel = D('Hawk/Admin');
    	$data = $amodel->search(10,$where);
        $part = $model
        ->table(C('DB_PREFIX').'part')
        ->select();
        $list = $model
        ->table(C('DB_PREFIX').'admin')
        ->select();
    	$this->assign(array(
            'list'=>$list,
            'search'=>$search,
            'part' => $part,
    		'data' => $data['data'],
    		'page' => $data['page'],
    	));
		$this->setPageBtn('管理员列表', '添加管理员', U('add'));
    	$this->display();
    }
    /**
     * 部门分配
     * @author hawk <2271030162@qq.com>
     * @return mix
     */
    public function allot(){
        if(IS_POST){
            $id = explode(',', $_POST['id']);
            if(is_array($id)){
                $data['part_id']=$_POST['part'];
                $model=M('Admin');
                for ($i=0; $i <count($id) ; $i++) {                  
                    $re = $model->where(array('id'=>array('eq',$id[$i])))->data($data)->save();
                }
                if($re!==false){
                    $content = "给-".$_POST['id']."-分配部门".$_POST['part']."成功";
                    hawk_operation_log(session('id'),hawk_get_ip(),$content);
                    echo json_encode(array('code'=>1,'msg'=>'操作成功！'));
                }else{
                    echo json_encode(array('code'=>0,'msg'=>'操作失败！'));
                }
            }else{
                $data['server_worker']=$_POST['businesser'];
                $model = M('Customer');
                $re = $model->where(array('id'=>array('eq',$id)))->data($data)->save($data);
                if($re!==false){
                    echo json_encode(array('code'=>1,'msg'=>$msg.'操作成功！'));
                }else{
                    echo json_encode(array('code'=>0,'msg'=>$msg.'操作失败！'));
                }
            }
        }else{
            $id = I('get.id');
            $pmodel = M('Part');
            $part = $pmodel->where(array('is_use'=>array('eq',1)))->select();
            $this->assign('part',$part);
            $this->assign('id',$id);
            $this->display();
        }
    }
    /**
     * 角色分配
     * @author hawk <2271030162@qq.com>
     * @return mix
     */
    public function allotrole(){
        if(IS_POST){
            $id = explode(',', $_POST['id']);
            if(is_array($id)){
                $data['role_id']=$_POST['role_id'];
                $model=M('AdminRole');
                for ($i=0; $i <count($id) ; $i++) {
                    $list = $model->where(array('admin_id'=>array('eq',$id[$i])))->select();
                    if(!empty($list)){
                        $re = $model->where(array('admin_id'=>array('eq',$id[$i])))->data($data)->save();
                    }else{
                        $data['admin_id']=$id[$i];
                        $re = $model->data($data)->add();
                    }                                      
                }
                if($re!==false){
                    $content = "给-".$_POST['id']."-分配角色".$_POST['part']."成功";
                    hawk_operation_log(session('id'),hawk_get_ip(),$content);
                    echo json_encode(array('code'=>1,'msg'=>'操作成功！'));
                }else{
                    echo json_encode(array('code'=>0,'msg'=>'操作失败！'));
                }
            }else{
                $data['server_worker']=$_POST['businesser'];
                $model = M('Customer');
                $re = $model->where(array('id'=>array('eq',$id)))->data($data)->save($data);
                if($re!==false){
                    echo json_encode(array('code'=>1,'msg'=>$msg.'操作成功！'));
                }else{
                    echo json_encode(array('code'=>0,'msg'=>$msg.'操作失败！'));
                }
            }
        }else{
            $id = I('get.id');
            $pmodel = M('Role');
            $role = $pmodel->select();
            $this->assign('role',$role);
            $this->assign('id',$id);
            $this->display();
        }
    }
    /**
     * 管理员信息excel文件上传
     * 文件名组成:[(Ymdhis)格式的日期+2位随机数+用户id]
     * @author hawk <2271030162@qq.com>
     * @return mix
     */
    public function upload(){ 
        if (IS_POST) {
                $file_size=$_FILES['file']['size'];
                if($file_size>3145728 ) {
                    echo json(array('code'=>1001,'msg'=>'上传文件超过上限3145728b'));exit;  
                }
                if ($_FILES['file']['error']==0){
                    $arr=Array('application/vnd.ms-excel','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
                    if (in_array($_FILES['file']['type'], $arr)){                     
                        $addtime = time(); 
                        $start = strrpos($_FILES['file']['name'], '.');//调整指针位置
                        $endstr = substr($_FILES['file']['name'], $start);//截取字符串
                        $r = rand(10,99);   //调取随机数
                        $name = date('Ymdhis',time()).$r.session('staff_info')['id'];
                        $names = $name.$endstr; //组合文件名
                        $filePath = UPLOAD_PATH.'admin/excel/'.date('Ymd',time()).'/';
                        $path = $filePath.$names;
                        if(!file_exists($filePath)) { 
                            mkdir($filePath,0777,true);  
                        } 
                        $a = move_uploaded_file($_FILES['file']['tmp_name'], $path);//临时文件转存到指定文件夹
                        if($a){
                            echo $this->_import($path);
                        }
                    }else{
                        echo json(array('code'=>1002,'msg'=>'仅允许上传xlsx、xls格式文件'));exit;   
                    }
                }else{
                    echo json(array('code'=>1003,'msg'=>'上传文件失败！'));exit;
                }
            
        }else{
            $this->display();
        }
    }
    /**
     * 管理员信息导入
     * @author hawk <2271030162@qq.com>
     * @return json
     */
    private function _import($file){
        $file = UPLOAD_PATH."staff.xlsx";
        $staff = hawk_import_excel($file);
        $title = array_filter($staff[1]);
        array_shift($staff);
        $model=M('');
        $model->startTrans();
        foreach ($staff as $k => $v){
            for ($i=0; $i <count($title) ; $i++) { 
                $admin[$k][$title[$i]]=$v[$i];
            }
            if(!empty($admin[$k]['username'])){
                $data = $model
                ->table(C('DB_PREFIX').'admin')
                ->where(array(
                    'username'=>array('eq',$admin[$k]['username'])
                    ))
                ->select();
                if(empty($data)){
                    $re_add = $model
                    ->table(C('DB_PREFIX').'admin')
                    ->data($admin[$k])
                    ->add();
                    if(!$re_add){
                        $model->rollback();
                        return json_encode(array('code'=>0,'msg'=>'导入失败，请联系管理员！'));
                        exit;
                    }
                }else{
                    $re_add = $model
                    ->table(C('DB_PREFIX').'admin_repeat')
                    ->data($admin[$k])
                    ->add();
                    if(!$re_add){
                        $model->rollback();
                        return json_encode(array('code'=>0,'msg'=>'去重失败，请联系管理员！'));
                        exit; 
                    }
                }
            }else{
                $model->rollback();
                return json_encode(array('code'=>500,'msg'=>'提交数据格式不正确，请使用excel模板！'));
                exit;
            }         
        }
        $model->commit();
        return json_encode(array('code'=>1,'msg'=>'导入成功！'));
        exit;     
    }
}